/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vn.edu.vttu;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.JOptionPane;
import java.util.Date;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author Lucas Nguyen
 */
public class Guimail extends javax.swing.JFrame {

    /**
     * Creates new form Guimail
     */
      private DefaultTableModel modelFileAttact;
       private long tongKichThuocCacFile = 0;
       private Vector<File> fileDinhKem = new Vector<File>();
       
       
         public Guimail() {
        initComponents();
          Vector<String> header = new Vector<String>();
        header.add("Tên file");
        header.add("Kích thước");
        modelFileAttact = new DefaultTableModel(null, header) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
       // ChiTietFile.setModel(modelFileAttact);
        dsfile.setModel(modelFileAttact);
        btGuimail.enable(false);
     TienTrinh.setBackground(Color.GREEN);
     TienTrinh.setStringPainted(true);
   //  TienTrinh.setValue(5);
    txtnguoigui.setText(ConnectionServer.userName);
    txtnguoigui.setEnabled(false);
    this.setTitle("Soạn thư mới");
    }

   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel6 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtnguoigui = new javax.swing.JTextField();
        txtnguoinhan = new javax.swing.JTextField();
        txttieude = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        lbadila = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        dsfile = new javax.swing.JTable();
        btthemfile = new javax.swing.JButton();
        btgofile = new javax.swing.JButton();
        tbtongfile = new javax.swing.JLabel();
        tbtongkichthuoc = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        teanoidung = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        btGuimail = new javax.swing.JButton();
        btnhaplai = new javax.swing.JButton();
        bthuymail = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        TienTrinh = new javax.swing.JProgressBar();
        TrangThai = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 255, 204));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 755, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 22, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("Tiêu đề: ");

        jLabel2.setText("Người nhận: ");

        jLabel1.setText("Người gửi:");

        txtnguoigui.setFont(new java.awt.Font("Tahoma", 3, 14)); // NOI18N
        txtnguoigui.setForeground(new java.awt.Color(204, 0, 0));
        txtnguoigui.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtnguoiguiKeyPressed(evt);
            }
        });

        txtnguoinhan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtnguoinhanKeyPressed(evt);
            }
        });

        txttieude.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txttieudeKeyPressed(evt);
            }
        });

        jLabel6.setText("Tên người dùng");

        lbadila.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lbadila.setForeground(new java.awt.Color(255, 0, 0));
        lbadila.setText("Group 5");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(255, 51, 51));
        jLabel7.setText("@nhom5.no-ip.org");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(255, 51, 51));
        jLabel8.setText("@nhom5.no-ip.org");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel6)
                    .addComponent(jLabel3))
                .addGap(57, 57, 57)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtnguoigui, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
                                .addComponent(txttieude))
                            .addComponent(txtnguoinhan, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)))
                    .addComponent(lbadila))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lbadila))
                .addGap(8, 8, 8)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtnguoigui, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtnguoinhan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txttieude, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        dsfile.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(dsfile);

        btthemfile.setBackground(new java.awt.Color(255, 153, 153));
        btthemfile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon-add.png"))); // NOI18N
        btthemfile.setText("  Thêm file");
        btthemfile.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btthemfile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btthemfileActionPerformed(evt);
            }
        });

        btgofile.setBackground(new java.awt.Color(51, 204, 255));
        btgofile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/delete1.png"))); // NOI18N
        btgofile.setText("  Gỡ bỏ");
        btgofile.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btgofile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btgofileActionPerformed(evt);
            }
        });

        tbtongfile.setText("Tổng số file là: ");

        tbtongkichthuoc.setText("Tổng kích thước");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btthemfile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btgofile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(tbtongfile)
                        .addGap(179, 179, 179)
                        .addComponent(tbtongkichthuoc)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(tbtongfile)
                            .addComponent(tbtongkichthuoc)))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btthemfile, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btgofile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        teanoidung.setColumns(20);
        teanoidung.setRows(5);
        jScrollPane1.setViewportView(teanoidung);

        jLabel4.setText("Nội dung");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 655, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addGap(114, 114, 114))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btGuimail.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btGuimail.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/256px-Email_Shiny_Icon.svg.png"))); // NOI18N
        btGuimail.setText("  Gửi mail");
        btGuimail.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        btGuimail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGuimailActionPerformed(evt);
            }
        });

        btnhaplai.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnhaplai.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/icon_xalo.png"))); // NOI18N
        btnhaplai.setText("  Nhập lại");
        btnhaplai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnhaplaiActionPerformed(evt);
            }
        });

        bthuymail.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        bthuymail.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/reboot lodo.jpg"))); // NOI18N
        bthuymail.setText("Hủy");
        bthuymail.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        bthuymail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bthuymailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(btGuimail)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnhaplai)
                .addGap(167, 167, 167)
                .addComponent(bthuymail, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btGuimail, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnhaplai)
                    .addComponent(bthuymail, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        TienTrinh.setBackground(new java.awt.Color(0, 255, 0));
        TienTrinh.setIndeterminate(true);

        TrangThai.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        TrangThai.setForeground(new java.awt.Color(102, 102, 255));
        TrangThai.setText("Loading.......");

        javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
        jPanel7.setLayout(jPanel7Layout);
        jPanel7Layout.setHorizontalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(TrangThai, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(TienTrinh, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel7Layout.setVerticalGroup(
            jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(TienTrinh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel7Layout.createSequentialGroup()
                .addComponent(TrangThai)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel7, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
/*
    public static void send
        (
            String smtpServer,
            String to,
            String from, 
            String psw,
            String subject,
            String body,
           Vector<File> filesAttact
    ) 
            throws Exception {
        

        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.starttls.enable", "true");
        //điền host và port 
        final String login = from;
        final String pwd = psw;
        Authenticator pa = null;
        
        if (login != null && pwd != null) {
            props.put("mail.smtp.auth", "true");
            pa = new Authenticator() {

       @Override
       public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(login, pwd);
                }
            };
        }
//else: no authentication
        
        Session session = Session.getInstance(props, pa);
        
// — Create a new message –
        
        Message msg = new MimeMessage(session);
        
// — Set the FROM and TO fields –
        
        msg.setFrom(new InternetAddress(from));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( to, false));

// — Set the subject and body text –
        
        msg.setSubject(subject);
        
//msg.setText(body);

        msg.setContent(body, "text/html; charset=UTF-8");
        
//Để gởi nội dung dạng utf-8 các  dùng msg.setContent(body, "text/html; charset=UTF-8");
        //Add file
        if (filesAttact != null) {
            if (filesAttact.size() > 0) {
                addAtachments(filesAttact, multipart);
            }
        }
// — Set some other header information –
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());
        msg.saveChanges();
        
// — Send the message –
        Transport.send(msg);
        System.out.println("Mail da duoc gui ùi đóa nha..main đó "); // thông báo thành công

    }
  */   
    /**
     * Gửi thông điệp
     *
     * @param from Địa chỉ gửi
     * @param alias Tên thay thế cho địa chỉ
     * @param psw Mật khẩu
     * @param to Địa chỉ tới
     * @param subject Chủ đề
     * @param body Phần thông điệp
     * @param filesAttact Danh sách các file cần đính kèm
     * @throws Exception
     */
  
     public void send(String from, String alias, String psw, String to,
            String subject, Object body, Vector<File> filesAttact) throws Exception {
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

         Session session = ConnectionServer.createSessionSMTP(from, psw);
     //   TienTrinh.setValue(10);
        
// — Create a new message –
        Message msg = new MimeMessage(session);
         
// — Set the FROM and TO fields –
        if (alias.isEmpty()) {
            alias = null;
        }
        msg.setFrom(new InternetAddress(from, alias));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, true));
        
        //Create a message part for the time,location
       
        MimeMultipart multipart = new MimeMultipart(); // toàn bộ  thân mail
        MimeBodyPart messagePart = new MimeBodyPart();
        String htmlText = teanoidung.getText();   //Email Body Text Content
        //Add nội dung
         
        messagePart.setText(htmlText, "UTF-8");// chèn nôi dung ở tea vào phân thân nhỏ

        multipart.addBodyPart(messagePart); // add toàn bộ vào thân lớn
        //Add file
       
        if (filesAttact != null) {
            if (filesAttact.size() > 0) {
                addAtachments(filesAttact, multipart);
            }
        }
  //     TienTrinh.setValue(50);
        TrangThai.setText("Đang gửi...");
// — Set the subject and body text –
        msg.setSubject(txttieude.getText());
        msg.setContent(multipart);
        msg.setSentDate(new Date());
        msg.saveChanges();
        
// — Send the message –
        Transport.send(msg);
      //     TienTrinh.setValue(100);
          System.out.println("Mai đã được gữi thành công..."); // thông báo thành công
    }

    
        /**
     * Đính kèm các file vào thư gửi
     *
     * @param attachments
     * @param mimeMultipart
     * @throws MessagingException
     * @throws AddressException
     */
    
    protected void addAtachments(Vector<File> attachments, MimeMultipart mimeMultipart)
            throws MessagingException, AddressException {
        int i = 0;
        for (File f : attachments) {
            i++;
            String filename = f.getAbsolutePath();
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            //use a JAF FileDataSource as it does MIME type detection
            FileDataSource source = new FileDataSource(filename);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            //assume that the filename you want to send is the same as the
            //actual file name - could alter this to remove the file path
            attachmentBodyPart.setFileName(f.getName());
            mimeMultipart.addBodyPart(attachmentBodyPart);
            TrangThai.setText("File thứ " + i + " (" + f.getName() + ")" + " đã được upload");
        }
    }
    
        public boolean kiemTraRong(){
         String nguoiGui= txtnguoigui.getText();
         String nguoiNhan = txtnguoinhan.getText();
         String chuDe= txttieude.getText();
         String noiDung= teanoidung.getText();
             if (nguoiGui == null || nguoiGui.equals("")) {
               JOptionPane.showMessageDialog(this, "Thiếu địa chỉ người gửi", "Error", JOptionPane.ERROR_MESSAGE);
               return  false;
             }
              if (nguoiNhan == null || nguoiNhan.equals("")) {
          
                 JOptionPane.showMessageDialog(this, "Thiếu địa chỉ người gữi", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
              if (chuDe.isEmpty()) {
           
                      int c = JOptionPane.showConfirmDialog(this, "Thư không có chủ đề. Bạn có muốn gửi không?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                     if (c == JOptionPane.NO_OPTION) {
                return false;
                }
                     
        } 
               if (noiDung.isEmpty()) {
           
                      int c = JOptionPane.showConfirmDialog(this, "Thư không có nội dung. Bạn có muốn gửi không?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                     if (c == JOptionPane.NO_OPTION) {
                return false;
                }
                     
        } 
             
             return true;
    
    }
         public String kiemTraDiaChiGmail(String diaChi) {
        if (diaChi == null || diaChi.isEmpty()) {
            return null;
        }
        diaChi = diaChi.toLowerCase();
        
        if (diaChi.endsWith("@nhom5.no-ip.org")) {
            return diaChi;
        } else {
            if (diaChi.indexOf('@') < 0) {
                return diaChi.concat("@nhom5.no-ip.org");
            }
        }
        return null;
    }
    private void btGuimailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGuimailActionPerformed
        // TODO add your handling code here:
        try {
               String smtpServer ="nhom5.no-ip.org";
                  String nguoiGui = txtnguoigui.getText();
               String nguoiNhan= txtnguoinhan.getText();
                 String tieuDe= txttieude.getText();
               String noiDung= teanoidung.getText();
     
    if(kiemTraRong()){
      if(kiemTraDiaChiGmail(nguoiGui) != null && kiemTraDiaChiGmail(nguoiNhan)!=null){
      
                 //   JOptionPane.showConfirmDialog(null, kiemTraDiaChiGmail(nguoiGui)+" "+kiemTraDiaChiGmail(nguoiNhan))
              //  send(smtpServer, kiemTraDiaChiGmail(nguoiNhan),kiemTraDiaChiGmail(nguoiGui), "1", tieuDe, noiDung);
              send(kiemTraDiaChiGmail(nguoiGui),lbadila.getText(), ConnectionServer.passWord,kiemTraDiaChiGmail(nguoiNhan) , tieuDe, noiDung, fileDinhKem);
                JOptionPane.showConfirmDialog(null, "Mail đã được gửi đến:"+kiemTraDiaChiGmail(nguoiNhan),"Thông báo",JOptionPane.YES_OPTION);
             //   this.hide();
                this.setVisible(false);
     

}
      else {
      JOptionPane.showMessageDialog(null, nguoiGui+ " không phải là địa chỉ nhom5.no-ip.org", "Error", JOptionPane.ERROR_MESSAGE);
          return;
      }
}
        } catch (Exception e) {
            e.printStackTrace();
          JOptionPane.showConfirmDialog(null, "Không kết nối được với: nhom5.no-ip.org, port: 25","Thông báo",JOptionPane.YES_OPTION,JOptionPane.ERROR_MESSAGE);

        
        }
       
        
    }//GEN-LAST:event_btGuimailActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
         this.setLocationRelativeTo(null);
 
    }//GEN-LAST:event_formWindowOpened

    private void bthuymailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bthuymailActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
        MainLayer main = new MainLayer();
        main.setEnabled(true);
        //main.setVisible(true);
    }//GEN-LAST:event_bthuymailActionPerformed

    private void btthemfileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btthemfileActionPerformed
        // TODO add your handling code here:
         JFileChooser jFileChooser = new JFileChooser();
        
           jFileChooser.setMultiSelectionEnabled(true);
          int c = jFileChooser.showOpenDialog(this);
           if (c == JFileChooser.CANCEL_OPTION) {
            return;
           }
              File[] fileArray = jFileChooser.getSelectedFiles();
        if (fileArray != null) {
            if (fileArray.length > 0) {
                try {
                    int index = 0;
                    for (final File f : fileArray) {
                        tongKichThuocCacFile += f.length();
                        if (f.length() / 1024 < 1024) {
                            modelFileAttact.addRow(new Object[]{f.getName(), f.length() < 1024 ? (double) f.length() + " Bytes" : (double) f.length() / 1024 + " Kbytes"});
                        } else {
                            modelFileAttact.addRow(new Object[]{f.getName(), (double) f.length() / 1024 / 1024 + " Mbytes"});
                        }
                        index++;
                    }
                    this.addFileArray(fileArray);
                    tbtongfile.setText("<html><body>Tổng số file gửi: <font color=blue>" + fileDinhKem.size() + (fileDinhKem.size() > 1 ? " files</font></body></html>" : " file</font></body></html>"));
                    if (tongKichThuocCacFile <= 1024) {
                        tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + (double) tongKichThuocCacFile + " bytes</font></body></html>");
                    } else if (tongKichThuocCacFile < 1024 * 1024) {
                        tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + ((double) tongKichThuocCacFile / 1024) + " Kbytes</font></body></html>");
                    } else {
                        tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + ((double) tongKichThuocCacFile / (1024 * 1024)) + " Mbytes</font></body></html>");
                    }

                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, e, "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        
    }//GEN-LAST:event_btthemfileActionPerformed

    private void btgofileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btgofileActionPerformed
        // TODO add your handling code here:
        if(fileDinhKem.size()>0){
          int[] rowSelected = dsfile.getSelectedRows();
        int removed = 0;
        for (int i : rowSelected) {
            modelFileAttact.removeRow(i - removed);
            tongKichThuocCacFile -= fileDinhKem.get(i - removed).length();
            fileDinhKem.remove(i - removed);
            removed++;
        }
        tbtongfile.setText("<html><body>Tổng số file gửi: <font color=blue>" + fileDinhKem.size() + (fileDinhKem.size() > 1 ? " files</font></body></html>" : " file</font></body></html>"));
        //Tính lại tổng kích thước
        if (tongKichThuocCacFile <= 1024) {
            tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + (double) tongKichThuocCacFile + " bytes</font></body></html>");
        } else if (tongKichThuocCacFile < 1024 * 1024) {
            tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + ((double) tongKichThuocCacFile / 1024) + " Kbytes</font></body></html>");
        } else {
            tbtongkichthuoc.setText("<html><body>Tổng kích thước: <font color=blue>" + ((double) tongKichThuocCacFile / (1024 * 1024)) + " Mbytes</font></body></html>");
        }
        if (fileDinhKem.size() == 0) {
            tbtongfile.setText("");
           tbtongkichthuoc.setText("");
        }}
        else {
            JOptionPane.showConfirmDialog(null,"Không có file","Erorr",JOptionPane.OK_OPTION,JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_btgofileActionPerformed

    private void txtnguoiguiKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnguoiguiKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      { 
          txtnguoinhan.requestFocus();
      }
    }//GEN-LAST:event_txtnguoiguiKeyPressed

    private void txtnguoinhanKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnguoinhanKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      { 
         txttieude.requestFocus();
      }
    }//GEN-LAST:event_txtnguoinhanKeyPressed

    private void txttieudeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txttieudeKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER)
      { 
          teanoidung.requestFocus();
      }
    }//GEN-LAST:event_txttieudeKeyPressed

    private void btnhaplaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnhaplaiActionPerformed
        // TODO add your handling code here:
        txtnguoigui.setText(null);
        txtnguoinhan.setText(null);
        txttieude.setText(null);
        teanoidung.setText(null);
    }//GEN-LAST:event_btnhaplaiActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
         this.setVisible(false);
    }//GEN-LAST:event_formWindowClosing

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_formWindowClosed
private void addFileArray(File[] files) {
        for (File f : files) {
            this.fileDinhKem.add(f);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Guimail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Guimail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Guimail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Guimail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Guimail().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar TienTrinh;
    private javax.swing.JLabel TrangThai;
    private javax.swing.JButton btGuimail;
    private javax.swing.JButton btgofile;
    private javax.swing.JButton bthuymail;
    private javax.swing.JButton btnhaplai;
    private javax.swing.JButton btthemfile;
    private javax.swing.JTable dsfile;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbadila;
    private javax.swing.JLabel tbtongfile;
    private javax.swing.JLabel tbtongkichthuoc;
    private javax.swing.JTextArea teanoidung;
    private javax.swing.JTextField txtnguoigui;
    private javax.swing.JTextField txtnguoinhan;
    private javax.swing.JTextField txttieude;
    // End of variables declaration//GEN-END:variables
}
